package com.cssl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cssl.pojo.*;
import com.cssl.pojo.Collections;
import com.cssl.service.*;
import com.cssl.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class PetController {

    @Autowired
    private UserpetService service;

    @Autowired
    private PetinfoService service1;

    @Autowired
    private OrderService service2;

    @Autowired
    private PetshopService service3;

    @Autowired
    private AdoptService service4;

    @Autowired
    private SeekService service5;

    @Autowired
    private FoundService service6;
    @Autowired
    private ForumService service7;

    @Autowired
    private CollectionService service8;

    @Autowired
    private MessageService service9;

    @Autowired
    private LikeService service10;


    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private MongoTemplate template;

    //我的宠物
    @RequestMapping("/mypetinfo")
    public IPage<Userpet> mypetinfo(HttpServletRequest req){
        HttpSession session = req.getSession();
        User u = (User) redisUtil.get(session.getId());
        LambdaQueryWrapper<Userpet> lqw = Wrappers.lambdaQuery();
        lqw.eq(Userpet::getUp_uid,u.getUid());
        return service.page(new Page<>(0,10L),lqw);
    }
    //我的宠物2
    @RequestMapping("/mypetinfo2")
    public IPage<Userpet> mypetinfo2(@RequestParam Integer status,HttpServletRequest req){
        HttpSession session = req.getSession();
        User u = (User) redisUtil.get(session.getId());
        LambdaQueryWrapper<Userpet> lqw = Wrappers.lambdaQuery();
        lqw.eq(Userpet::getUp_uid,u.getUid());
        lqw.eq(Userpet::getUp_status,status);
        return service.page(new Page<>(0,10L),lqw);
    }

    //单个品种信息
    @RequestMapping("/petinfoOne")
    public Petinfo mypetinfo(@RequestParam Integer bid){
        return service1.getById(bid);
    }

    //单个宠物详情
    @RequestMapping("/petdetail")
    public Userpet petdetail(@RequestParam int upid){
        return service.getById(upid);
    }
    //品种
    @RequestMapping("/petpz")
    public List<Petinfo> petpz(){
        //查询mongodb已存储的品种
        List<Petinfo> pt = template.findAll(Petinfo.class);
        if(pt == null || pt.size()==0){
            template.save(service1.list());
        }
        List<Petinfo> list = template.findAll(Petinfo.class);
        return list;
    }

    //修改我的宠物信息  状态
    @RequestMapping("/updatestatus")
    public Boolean updatestatus(@RequestParam Integer upid,@RequestParam Integer status){
        Userpet up = new Userpet();
        up.setUpid(upid);
        up.setUp_status(status);
        return service.updateById(up);
    }
    //修改我的宠物信息  状态
    @RequestMapping("/updatestatus2")
    public Boolean updatestatus2(@RequestParam String upids){
        String[] nums = upids.split(",");
        int[] array = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            array[i] = Integer.parseInt(nums[i]);
        }
        for (int num:array) {
            Userpet ups = new Userpet();
            ups.setUpid(num);
            ups.setUp_status(0);
            service.updateById(ups);//修改宠物状态（0：默认）
        }
        return true;
    }

    //修改宠物信息
    @RequestMapping("/updatepetinfo")
    public Boolean upload(@RequestParam MultipartFile files, @RequestParam Map<String, Object> map)
            throws IllegalStateException, IOException, ParseException {
        // 从请求上下文里获取Request对象
        ServletRequestAttributes requestAttributes = ServletRequestAttributes.class.cast(RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        User u =(User)redisUtil.get(session.getId());
        System.out.println("map:"+map);
        int upid = Integer.parseInt(map.get("upid").toString());
        String petname = map.get("upname").toString();
        String sex = map.get("upsex").toString();
        String upbid = map.get("upbid").toString();
        String email = map.get("upemail").toString();
        String address = map.get("upaddress").toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(map.get("upborndate").toString());
       Userpet up = new Userpet();
       up.setUpid(upid);
       up.setUp_address(address);
       up.setUpborndate(date);
       up.setUp_email(email);
       up.setUp_uid(u.getUid());
       up.setUp_bid(Integer.parseInt(upbid));
       up.setUpsex(sex);
       up.setUpname(petname);
        String path = "D:\\nginx\\nginx-1.25.0\\html\\pet\\images\\";
        List<String> types =new ArrayList<>();
        types.add("image/jpeg");
        types.add("image/gif");
        types.add("image/png");
        String type = files.getContentType();
        double size = files.getSize() * 1.0 / 1024 / 1024;
        String fileName = UUID.randomUUID().toString() + files.getOriginalFilename();
        System.out.println("filename:"+fileName);
        up.setUp_file(fileName);
        if (types.contains(type) && size <= 3) {
            files.transferTo(new File(path + fileName));
            System.out.println("bool:"+service.updateById(up));
            return service.updateById(up);
        } else {
            System.out.println("文件类型或大小不允许");
        }
        return false;
    }

    //添加宠物信息
    @RequestMapping("/addpetinfo")
    public Boolean addpet(@RequestParam MultipartFile files, @RequestParam Map<String, Object> map)
            throws IllegalStateException, IOException, ParseException {
        // 从请求上下文里获取Request对象
        ServletRequestAttributes requestAttributes = ServletRequestAttributes.class.cast(RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        User u =(User)redisUtil.get(session.getId());
        System.out.println("map:"+map);
        String petname = map.get("pname").toString();
        String sex = map.get("upsex").toString();
        String upbid = map.get("upbid").toString();
        String email = map.get("upemail").toString();
        String address = map.get("upaddress").toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(map.get("upborndate").toString());
        Userpet up = new Userpet();
        up.setUp_address(address);
        up.setUpborndate(date);
        up.setUp_email(email);
        up.setUp_uid(u.getUid());
        up.setUp_bid(Integer.parseInt(upbid));
        up.setUpsex(sex);
        up.setUpname(petname);
        String path = "D:\\nginx\\nginx-1.25.0\\html\\pet\\images\\";
        List<String> types =new ArrayList<>();
        types.add("image/jpeg");
        types.add("image/gif");
        types.add("image/png");
        String type = files.getContentType();
        double size = files.getSize() * 1.0 / 1024 / 1024;
        String fileName = UUID.randomUUID().toString() + files.getOriginalFilename();
        System.out.println("filename:"+fileName);
        up.setUp_file(fileName);
        if (types.contains(type) && size <= 3) {
            files.transferTo(new File(path + fileName));
            System.out.println("bool:"+service.updateById(up));
            return service.save(up);
        } else {
            System.out.println("文件类型或大小不允许");
        }
        return false;
    }

    //我的订单
    @RequestMapping("/myorder")
    public IPage<Orders> myorder(HttpServletRequest req){
        HttpSession session  = req.getSession();
        User user =(User) redisUtil.get(session.getId());
        LambdaQueryWrapper<Orders> lqw = Wrappers.lambdaQuery();
        lqw.eq(Orders::getO_uid,user.getUid());
        lqw.eq(Orders::getIsdel,0);
        lqw.orderByDesc(Orders::getOdate);
        //暂时10
        return service2.page(new Page<>(0,20),lqw);
    }
    //所有店铺
    @RequestMapping("/petshop")
    public List<Petshop> delorder(){
        return service3.list();
    }
    //订单详情
    @RequestMapping("/orderdetail")
    public Orders orderdetail(@RequestParam int oid){
        return service2.getById(oid);
    }

    //订单详情
    @RequestMapping("/orderdetail2")
    public Orders orderdetail2(@RequestParam String orderid){
        LambdaQueryWrapper<Orders> lqw = Wrappers.lambdaQuery();
        lqw.eq(Orders::getOrderid,orderid);

        return service2.getOne(lqw);
    }


    //删除订单  改变我的宠物状态
    @RequestMapping("/delorder")
    public Boolean delorder(@RequestParam int oid){
       Orders od = service2.getById(oid);
       String upids = od.getUpids();
       String[] nums = upids.split(",");
       int[] array = new int[nums.length];
       for (int i = 0; i < nums.length; i++) {
            array[i] = Integer.parseInt(nums[i]);
       }
       for (int num:array) {
            Userpet up = new Userpet();
            up.setUpid(num);
            up.setUp_status(0);
            service.updateById(up);
        }
       Orders os  =new Orders();
       os.setOid(oid);
       os.setIsdel(1);
       //逻辑删除
       return service2.updateById(os);
    }

    //我的求领养
    @RequestMapping("/myadopt")
    public IPage<Adopt> myadopt(HttpServletRequest req){
        HttpSession session  = req.getSession();
        User user =(User) redisUtil.get(session.getId());
        LambdaQueryWrapper<Adopt> lqw = Wrappers.lambdaQuery();
        lqw.eq(Adopt::getA_uid,user.getUid());
        return service4.page(new Page<>(0,20),lqw);
    }
    //求领养详情
    @RequestMapping("/adoptdetail")
    public Adopt adoptdetail(@RequestParam int aid){
        return service4.getById(aid);
    }
    //修改领养详情
    @RequestMapping("/upadoptdetail")
    public Boolean upadoptdetail(@RequestParam MultipartFile files, @RequestParam Map<String, Object> map)
            throws IllegalStateException, IOException, ParseException {
        // 从请求上下文里获取Request对象
        ServletRequestAttributes requestAttributes = ServletRequestAttributes.class.cast(RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        User u =(User)redisUtil.get(session.getId());
        System.out.println("map:"+map);
        String atitle = map.get("atitle").toString();
        String petdz = map.get("petdz").toString();
        String lxr = map.get("lxr").toString();
        String lxdh = map.get("lxdh").toString();
        int upid = Integer.parseInt(map.get("upid").toString());
        int aid = Integer.parseInt(map.get("aid").toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(map.get("fbdate").toString());
        Adopt adopt = new Adopt();
        adopt.setAtitle(atitle);
        adopt.setAddress(petdz);
        adopt.setContact(lxr);
        adopt.setAphone(lxdh);
        adopt.setAdate(date);
        adopt.setUpid(upid);
        adopt.setA_uid(u.getUid());
        adopt.setAid(aid);
        String path = "D:\\nginx\\nginx-1.25.0\\html\\pet\\images\\";
        List<String> types =new ArrayList<>();
        types.add("image/jpeg");
        types.add("image/gif");
        types.add("image/png");
        String type = files.getContentType();
        double size = files.getSize() * 1.0 / 1024 / 1024;
        String fileName = UUID.randomUUID().toString() + files.getOriginalFilename();
        System.out.println("filename:"+fileName);
        adopt.setAfile(fileName);
        if (types.contains(type) && size <= 3) {
            files.transferTo(new File(path + fileName));
            return service4.updateById(adopt);
        } else {
            System.out.println("文件类型或大小不允许");
        }
        return false;
    }
    //删除求领养
    @RequestMapping("/deladopt")
    public Boolean deladopt(@RequestParam int aid){
        Adopt ad = service4.getById(aid);
        Userpet up = new Userpet();
        up.setUpid(ad.getUpid());
        up.setUp_status(0);
        service.updateById(up);
        return service4.removeById(aid);
    }

    //我的寻宠启事
    @RequestMapping("/myseek")
    public IPage<Seek> myseek(HttpServletRequest req){
        HttpSession session = req.getSession();
        User user =(User) redisUtil.get(session.getId());
        LambdaQueryWrapper<Seek> lqw = Wrappers.lambdaQuery();
        lqw.eq(Seek::getS_uid,user.getUid());
        return service5.page(new Page<>(0,20),lqw);
    }

    //寻宠详情
    @RequestMapping("/sdetail")
    public Seek sdetail(@RequestParam int seekid){
        return service5.getById(seekid);
    }
    //修改寻宠详情
    @RequestMapping("/upsdetail")
    public Boolean upsdetail(@RequestParam MultipartFile files, @RequestParam Map<String, Object> map)
            throws IllegalStateException, IOException, ParseException {
        // 从请求上下文里获取Request对象
        ServletRequestAttributes requestAttributes = ServletRequestAttributes.class.cast(RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        User u =(User)redisUtil.get(session.getId());
        System.out.println("map:"+map);
        String stitle = map.get("stitle").toString();
        String sdz = map.get("sdz").toString();
        String sdh = map.get("sdh").toString();
        String detail = map.get("detail").toString();
        int upid = Integer.parseInt(map.get("upid").toString());
        int seekid = Integer.parseInt(map.get("seekid").toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(map.get("sdate").toString());
       Seek sk = new Seek();
       sk.setS_uid(u.getUid());
       sk.setSeekaddress(sdz);
       sk.setSeekid(seekid);
       sk.setSeekdate(date);
       sk.setSeekphone(sdh);
       sk.setSeektitle(stitle);
       sk.setS_upid(upid);
       sk.setSeekdetail(detail);
        String path = "D:\\nginx\\nginx-1.25.0\\html\\pet\\images\\";
        List<String> types =new ArrayList<>();
        types.add("image/jpeg");
        types.add("image/gif");
        types.add("image/png");
        String type = files.getContentType();
        double size = files.getSize() * 1.0 / 1024 / 1024;
        String fileName = UUID.randomUUID().toString() + files.getOriginalFilename();
        System.out.println("filename:"+fileName);
        sk.setSeekfile(fileName);
        if (types.contains(type) && size <= 3) {
            files.transferTo(new File(path + fileName));
            return service5.updateById(sk);
        } else {
            System.out.println("文件类型或大小不允许");
        }
        return false;
    }
    //删除寻宠
    @RequestMapping("/delseek")
    public Boolean delseek(@RequestParam int seekid){
        return service5.removeById(seekid);
    }


    //我的招领启事
    @RequestMapping("/myfound")
    public IPage<Found> myfound(HttpServletRequest req){
        HttpSession session = req.getSession();
        User user =(User) redisUtil.get(session.getId());
        LambdaQueryWrapper<Found> lqw = Wrappers.lambdaQuery();
        lqw.eq(Found::getF_uid,user.getUid());
        return service6.page(new Page<>(0,20),lqw);
    }

    //寻宠详情
    @RequestMapping("/fdetail")
    public Found fdetail(@RequestParam int fid){
        return service6.getById(fid);
    }
    //修改寻宠详情
    @RequestMapping("/upfdetail")
    public Boolean upfdetail(@RequestParam MultipartFile files, @RequestParam Map<String, Object> map)
            throws IllegalStateException, IOException, ParseException {
        // 从请求上下文里获取Request对象
        ServletRequestAttributes requestAttributes = ServletRequestAttributes.class.cast(RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        User u =(User)redisUtil.get(session.getId());
        System.out.println("map:"+map);
        String stitle = map.get("ftitle").toString();
        String sdz = map.get("fdz").toString();
        String sdh = map.get("fdh").toString();
        String detail = map.get("detail").toString();
        int bid = Integer.parseInt(map.get("bid").toString());
        int fid = Integer.parseInt(map.get("fid").toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(map.get("fdate").toString());
        Found fd = new Found();
        fd.setFid(fid);
        fd.setFoundaddress(sdz);
        fd.setFounddate(date);
        fd.setFounddetail(detail);
        fd.setFoundphone(sdh);
        fd.setF_uid(u.getUid());
        fd.setFoundtitle(stitle);
        fd.setF_bid(bid);
        String path = "D:\\nginx\\nginx-1.25.0\\html\\pet\\images\\";
        List<String> types =new ArrayList<>();
        types.add("image/jpeg");
        types.add("image/gif");
        types.add("image/png");
        String type = files.getContentType();
        double size = files.getSize() * 1.0 / 1024 / 1024;
        String fileName = UUID.randomUUID().toString() + files.getOriginalFilename();
        System.out.println("filename:"+fileName);
        fd.setFoundfile(fileName);
        if (types.contains(type) && size <= 3) {
            files.transferTo(new File(path + fileName));
            return service6.updateById(fd);
        } else {
            System.out.println("文件类型或大小不允许");
        }
        return false;
    }
    //删除寻宠
    @RequestMapping("/delfound")
    public Boolean delfound(@RequestParam int fid){
        return service6.removeById(fid);
    }

    //我的贴子
    @RequestMapping("/myforum")
    public IPage<Forum> myforum(HttpServletRequest req){
        HttpSession session = req.getSession();
        User user =(User) redisUtil.get(session.getId());
        LambdaQueryWrapper<Forum> lqw = Wrappers.lambdaQuery();
        lqw.eq(Forum::getFb_uid,user.getUid());
        return service7.page(new Page<>(0,20),lqw);
    }

    //帖子详情
    @RequestMapping("/forumdetail")
    public Forum forumdetail(@RequestParam Integer forumid){
        return service7.getById(forumid);
    }
    //修改帖子详情
    @RequestMapping("/upforumdetail")
    public Boolean upforumdetail(@RequestParam MultipartFile files, @RequestParam Map<String, Object> map)
            throws IllegalStateException, IOException, ParseException {
        // 从请求上下文里获取Request对象
        ServletRequestAttributes requestAttributes = ServletRequestAttributes.class.cast(RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        User u =(User)redisUtil.get(session.getId());
        System.out.println("map:"+map);
        String stitle = map.get("forumtitle").toString();
        String detail = map.get("detail").toString();
        int forumid = Integer.parseInt(map.get("forumid").toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(map.get("fbdate").toString());
        Forum fm = new Forum();
        fm.setFb_audit(0);
        fm.setForumid(forumid);
        fm.setFbdate(date);
        fm.setFb_uid(u.getUid());
        fm.setForumtitle(stitle);
        fm.setForumdetail(detail);
        String path = "D:\\nginx\\nginx-1.25.0\\html\\pet\\images\\";
        List<String> types =new ArrayList<>();
        types.add("image/jpeg");
        types.add("image/gif");
        types.add("image/png");
        String type = files.getContentType();
        double size = files.getSize() * 1.0 / 1024 / 1024;
        String fileName = UUID.randomUUID().toString() + files.getOriginalFilename();
        System.out.println("filename:"+fileName);
        fm.setFb_file(fileName);
        if (types.contains(type) && size <= 3) {
            files.transferTo(new File(path + fileName));
            return service7.updateById(fm);
        } else {
            System.out.println("文件类型或大小不允许");
        }
        return false;
    }
    //删除帖子
    @RequestMapping("/delforum")
    public Boolean delforum(@RequestParam int forumid){
        return service7.removeById(forumid);
    }

    //我的收藏
    @RequestMapping("/mycoll")
    public IPage<Collections> mycoll(HttpServletRequest req){
        HttpSession session = req.getSession();
        User user =(User) redisUtil.get(session.getId());
        LambdaQueryWrapper<Collections> lqw = Wrappers.lambdaQuery();
        lqw.eq(Collections::getCo_uid,user.getUid());
        lqw.orderByDesc(Collections::getCodate);
        return service8.page(new Page<>(0,20),lqw);
    }

    //我发送
    @RequestMapping("/mymsg")
    public IPage<Message> mymsg(HttpServletRequest req){
        HttpSession session = req.getSession();
        User u = (User) redisUtil.get(session.getId());
        LambdaQueryWrapper<Message> lqw = Wrappers.lambdaQuery();
        lqw.eq(Message::getC_uid,u.getUid());
        lqw.orderByDesc(Message::getMsgdate);
        return service9.page(new Page<>(0,20),lqw);
    }

    //我接收
    @RequestMapping("/youmsg")
    public IPage<Message> youmsg(HttpServletRequest req){
        HttpSession session = req.getSession();
        User u = (User) redisUtil.get(session.getId());
        LambdaQueryWrapper<Message> lqw = Wrappers.lambdaQuery();
        lqw.eq(Message::getC_u_id,u.getUid());
        lqw.orderByDesc(Message::getMsgdate);
        return service9.page(new Page<>(0,20),lqw);
    }

    //发送消息详情
    @RequestMapping("/msgdetail")
    public Message msgdetail(@RequestParam int cid){
        return service9.getById(cid);
    }

    //删除发送消息
    @RequestMapping("/delmymsg")
    public Boolean delmymsg(@RequestParam int cid){
        return service9.removeById(cid);
    }

    //发送消息详情
    @RequestMapping("/youmsgdetail")
    public Message youmsgdetail(@RequestParam int cid){
        return service9.getById(cid);
    }

    //删除发送消息
    @RequestMapping("/delyoumsg")
    public Boolean delyoumsg(@RequestParam int cid){
        return service9.removeById(cid);
    }

    //修改已读
    @RequestMapping("/upread")
    public Boolean upread(@RequestParam int cid,@RequestParam int read){
        Message msg = new Message();
        msg.setCid(cid);
        msg.setIsread(read);
        return service9.updateById(msg);
    }

    //我的喜欢
    @RequestMapping("/mylike")
    public IPage<Like> mylike(HttpServletRequest request){
        HttpSession session =request.getSession();
        User u = (User)redisUtil.get(session.getId());
        LambdaQueryWrapper<Like> lqw = Wrappers.lambdaQuery();
        lqw.eq(Like::getLike_uid,u.getUid());
        lqw.orderByDesc(Like::getLikedate);
        return service10.page(new Page<>(0,10),lqw);
    }


}
